package cn.gzjp.common.baidu;


import com.alibaba.fastjson.JSONArray;
import org.apache.commons.io.FilenameUtils;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 语音识别
 */
public class AsrMain {

    //  填写网页上申请的appkey 如 $apiKey="g8eBUMSokVB1BHGmgxxxxxx"
    private final String appKey = "dbsQw7WD4V40FFAlVvmo13PC4M2Y2ZEA";

    // 填写网页上申请的APP SECRET 如 $secretKey="94dc99566550d87f8fa8ece112xxxxx"
    private final String secretKey = "PBFIefMQsl2Ajh5G938fg0FZR5Aqz2EI";


    //  1537 表示识别普通话，使用输入法模型。1536表示识别普通话，使用搜索模型。 其它语种参见文档
    private final int dev_pid = 1537;

    private String cuid = "1234567JAVA";
 
 // 采样率固定值
    private final int rate = 16000;
	
    public boolean methodRaw = false; // 默认以json方式上传音频文件

    private final String url = "http://vop.baidu.com/server_api"; // 可以改为https

    public String run(String filename,String format) throws IOException, DemoException {
        TokenHolder holder = new TokenHolder(appKey, secretKey, TokenHolder.ASR_SCOPE);
        holder.resfresh();
        String token = holder.getToken();
        String result = runJsonPostMethod(token,filename,format);
        return result;
    }


    public String runJsonPostMethod(String token,String filename,String format) throws DemoException, IOException {

        byte[] content = getFileContent(filename);
        String speech = base64Encode(content);

        JSONObject params = new JSONObject();
        params.put("dev-pid", dev_pid);
        params.put("format", format);
        params.put("rate", rate);
        params.put("token", token);
        params.put("cuid", cuid);
        params.put("channel", "1");
        params.put("len", content.length);
        params.put("speech", speech);

        // System.out.println(params.toString());
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        conn.setDoOutput(true);
        conn.getOutputStream().write(params.toString().getBytes());
        conn.getOutputStream().close();
        String result = ConnUtil.getResponseString(conn);
        return result;
    }

    private byte[] getFileContent(String filename) throws DemoException, IOException {
        File file = new File(filename);
        if (!file.canRead()) {
            System.err.println("文件不存在或者不可读: " + file.getAbsolutePath());
            throw new DemoException("file cannot read: " + file.getAbsolutePath());
        }
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            return ConnUtil.getInputStreamContent(is);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private String base64Encode(byte[] content) {
        /**
         Base64.Encoder encoder = Base64.getEncoder(); // JDK 1.8  推荐方法
         String str = encoder.encodeToString(content);
         **/

        char[] chars = Base64Util.encode(content); // 1.7 及以下，不推荐，请自行跟换相关库
        String str = new String(chars);

        return str;
    }


    public static void main(String[] args) throws IOException, DemoException {


        // 需要识别的文件
//        String filename = "/Users/jpzh/Develop/1.pcm";
//        String format = FilenameUtils.getExtension(filename);
//        System.out.println(format);
//        // 文件格式
//        AsrMain demo = new AsrMain();
//        String json = demo.run(filename,format);
//        System.out.println("识别结束：结果是："+json);
//        com.alibaba.fastjson.JSONObject obj = com.alibaba.fastjson.JSONObject.parseObject(json);
//        if (obj.get("err_no").toString().equals("0")) {
//            String result = obj.getString("result");
//            System.out.println("识别结束：结果是："+result);
//        } else {
//
//        }
        String s="[\\\"从始发地福建泉州发往目的地河南郑州，\\\"]";
        s = s.replaceAll("\\[","").replaceAll("]","").replaceAll("\\\\","").replaceAll("\"","");
        System.out.println(s);



    }

    public static String voiceToWords(String filename){
        String format = FilenameUtils.getExtension(filename);
        System.out.println(format);
        // 文件格式
        AsrMain demo = new AsrMain();
        String json = null;
        try {
            json = demo.run(filename,format);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DemoException e) {
            e.printStackTrace();
        }
        System.out.println("识别结束：结果是："+json);
        String result="";
        com.alibaba.fastjson.JSONObject obj = com.alibaba.fastjson.JSONObject.parseObject(json);
        if (obj.get("err_no").toString().equals("0")) {
            result = obj.getString("result");
            System.out.println("识别结束：结果是："+result);
        } else {
            result =  "该语音无法识别";
        }
        return result;
    }


}
